# -*- coding: utf-8 -*-
import configparser
import os
import json

config = configparser.ConfigParser()
current_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(current_dir, 'config.ini')


config = configparser.ConfigParser()
with open(config_path, 'r', encoding='utf-8-sig') as f:
    config.read_file(f)


# 获取 ini 文件中多个键的值
def getinivalue(section, *args):
    if len(args) == 1 and isinstance(args[0], list):
        args = args[0]  # 解包 list
    values = []
    for arg in args:
        try:
            value = config.get(section, arg)
        except Exception as e:
            raise ValueError(f"读取配置项失败 section=[{section}], key=[{arg}]，错误：{e}")
        values.append(str(value))
    return values


# 获取整个 section 为 dict，可选是否自动 JSON 解析值
def getjson(section, parse_json=False):
    result = {}
    for key, value in config.items(section):
        try:
            result[key] = json.loads(value) if parse_json else str(value)
        except json.JSONDecodeError:
            result[key] = str(value)
    return result


# 写入 ini 文件，自动将值转为字符串
def opinivalue(section, **kwargs):
    global config
    with open(config_path, 'r', encoding='utf-8-sig') as f:
        config.read_file(f)
    if not config.has_section(section):
        config.add_section(section)

    for key, value in kwargs.items():
        try:
            config.set(section, key, str(value))
        except Exception as e:
            raise ValueError(f"写入配置失败 section=[{section}], key=[{key}], 错误：{e}")

    with open(config_path, mode='w', encoding='utf-8-sig') as f:
        config.write(f)
